const cryptoJS = require('./cryptoJS')
const rsaJS = require('./rsaJS')

class crypto {

	encryptAES(data, key, iv) {
		try {
			data = cryptoJS.enc.Utf8.parse(data)
			key = cryptoJS.enc.Utf8.parse(key)
			iv = cryptoJS.enc.Utf8.parse(iv)
			const encrypted = cryptoJS.AES.encrypt(data, key, { iv, mode: cryptoJS.mode.CBC, padding: cryptoJS.pad.Pkcs7 })
			return encrypted.toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1068', msg: 'encrypt data failed' }
		}
	}

	decryptAES(data, key, iv) {
		try {
			key = cryptoJS.enc.Utf8.parse(key)
			iv = cryptoJS.enc.Utf8.parse(iv)
			const decrypted = cryptoJS.AES.decrypt(data, key, { iv, mode: cryptoJS.mode.CBC, padding: cryptoJS.pad.Pkcs7 })
			const decryptedStr = decrypted.toString(cryptoJS.enc.Utf8)
			return decryptedStr.toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1069', msg: 'decrypt data failed' }
		}
	}

	encryptRSA(data, key) {
		rsaJS.setPublicKey(key)
		return rsaJS.encrypt(data)
	}



	md5(data) {
		try {
			return cryptoJS.MD5(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1058', msg: 'encrypt data failed' }
		}
	}

	sha1(data) {
		try {
			return cryptoJS.SHA1(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1055', msg: 'encrypt data failed' }
		}
	}

	sha256(str) {
		try {
			return cryptoJS.SHA256(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1056', msg: 'encrypt data failed' }
		}
	}

	sha512(str) {
		try {
			return cryptoJS.SHA512(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1056', msg: 'encrypt data failed' }
		}
	}

	decodeBase64(data) {
		const buffer = wx.base64ToArrayBuffer(data)
		console.log(buffer, data)
		return String.fromCharCode.apply(null, new Unint8Array(buffer))
	}

}

module.exports = new crypto